﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using DataLayer.Entities;
using DataLayer.Implementations;
using DonutMgmtSystemFoundation.Models;
using ViewRes;

namespace DonutMgmtSystemFoundation.Helpers
{
    public class DonutsHelper
    {
        public IList<Donut> GetActiveDonuts()
        {
            DonutApplication app = new DonutApplication();

            return app.GetActiveDonuts();
        }

        public GeneralJsonResultModel UpdatePreferences(List<DonutOrderModel> donutsOrder, User user)
        {
            try
            {
                List<DonutPreference> preferences = new List<DonutPreference>();

                if (donutsOrder != null)
                {
                    foreach (DonutOrderModel item in donutsOrder)
                    {
                        preferences.Add(new DonutPreference()
                        {
                            Donut = new Donut() { DonutId = item.DonutId },
                            User = new User() { UserId = user.UserId },
                            OrderNumber = item.OrderNum
                        });
                    }
                    DonutPrefApplication app = new DonutPrefApplication();

                    // Delete prior preferences
                    List<DonutPreference> oldPrefs = (List<DonutPreference>)app.GetByUserId(user.UserId.Value);
                    app.Delete(oldPrefs);

                    // Save new preferences
                    app.Save(preferences);
                }
                else
                {
                    DonutPrefApplication app = new DonutPrefApplication();

                    // Delete prior preferences
                    List<DonutPreference> oldPrefs = (List<DonutPreference>)app.GetByUserId(user.UserId.Value);
                    app.Delete(oldPrefs);
                }
                return new GeneralJsonResultModel(true, Donuts.SavedSuccess);
            }
            catch
            {
                return new GeneralJsonResultModel(false, Donuts.SavedError);
            }
        }

        public GeneralJsonResultModel UpdateRandomPreferences()
        {
            try
            {
                UserApplication userApp = new UserApplication();
                User user = SessionContext.GetUserData();
                user.PrefersRandom = !user.PrefersRandom;
                userApp.Save(user);

                return new GeneralJsonResultModel(true, Donuts.SavedSuccess);
            }
            catch
            {
                return new GeneralJsonResultModel(false, Donuts.SavedError);
            }
        }

        public List<UserDonutsModel> GetUsersDonuts()
        {
            DonutPrefApplication app = new DonutPrefApplication();
            List<DonutPreference> orderList = (List<DonutPreference>)app.GetAll();
            if (orderList != null)
            {
                orderList = orderList
                .Where(x => x.User.IsActive && x.Donut.IsActive)
                .OrderBy(x => x.User.UserId)
                .ThenBy(x => x.OrderNumber)
                .ToList();

                // Seleccionar usuarios distintos y sin donas aleatorias
                UserApplication userApp = new UserApplication();
                List<User> notRandomDonutsUsers = (List<User>)userApp.GetRandomDonutsUsers(false);
                List<User> notRandomDonutsUsersinList = (from l in orderList
                                                         join user in notRandomDonutsUsers
                             on l.User.UserId equals user.UserId
                                                         where l.User.IsActive == true
                                                         select l.User).Distinct().ToList();

                List<User> randomDonutsUsers = (List<User>)userApp.GetRandomDonutsUsers(true);
                randomDonutsUsers = randomDonutsUsers.Where(x => x.IsActive).ToList();

                List<UserDonutsModel> model = new List<UserDonutsModel>();

                // Agregar usuarios sin donas aleatorias
                foreach (User u in notRandomDonutsUsersinList)
                {
                    var listByUser = (from o in orderList
                                      where o.User.UserId == u.UserId
                                      select o).ToList();
                    List<Donut> donuts = new List<Donut>();
                    foreach (DonutPreference d in listByUser)
                    {
                        donuts.Add(d.Donut);
                    }
                    model.Add(new UserDonutsModel()
                    {
                        User = u,
                        Donuts = donuts
                    });
                }

                // Agregar usuarios con donas aleatorias
                DonutApplication dApp = new DonutApplication();
                Random rand = new Random();
                foreach (User u in randomDonutsUsers)
                {
                    List<Donut> donuts = new List<Donut>();
                    List<Donut> active = (List<Donut>)dApp.GetActiveDonuts();                    
                    active = active.OrderBy(x => rand.Next()).ToList();

                    int max = active.Count > 2 ? 3 : active.Count;
                    for (int i = 0; i < max; i++)
                    {
                        donuts.Add(active[i]);
                    }
                    model.Add(new UserDonutsModel()
                    {
                        User = u,
                        Donuts = donuts
                    });
                }

                return model;
            }
            return null;

        }

        public DonutListsModel GetDonutLists()
        {
            DonutApplication app = new DonutApplication();
            IList<Donut> available = app.GetActiveDonuts();
            DonutPrefApplication appPref = new DonutPrefApplication();
            User user = SessionContext.GetUserData();
            IList<DonutPreference> preferences = appPref.GetByUserId(user.UserId.Value);
            preferences = preferences
                .Where(x => x.Donut.IsActive)
                .ToList();
            available = available.
                Where(a => !preferences.Any(p => p.Donut.DonutId == a.DonutId))
                .ToList();

            return new DonutListsModel()
            {
                AvailableDonuts = (List<Donut>)available,
                PreferedDonuts = (List<DonutPreference>)preferences
            };
        }


    }
}